$(function () {
    getCategoryList()
    function getCategoryList() {
        $.ajax({
            url: "/admin/category/list",
            // type: 'get',
            headers: { Authorization: localStorage.getItem("token") },
            success(res) {
                const list = res.data
                const html = template("tr", { list })
                $('.category_table tbody').html(html)
            }
        })
    }
    $('#save').on('click', function () {
        const name = $("[name='name']").val().trim()
        const slug = $("[name='slug']").val().trim()
        if (!name || !slug) {
            return
        }
        $.ajax({
            url: "/admin/category/add",
            type: "post",
            data: { name, slug },
            success(res) {
                layer.msg('新增成功');
                getCategoryList()
                $('.modal').modal('hide')
                $("[name='name']").val('')
                $("[name='slug']").val('')
            }
        })
    })

    $('.category_table').on('click', '.edit', function () {
        $('#editModal').modal('show')
        const item = $(this).data('item')
        const id = item.id
        console.log(id);
        const name = item.name
        const slug = item.slug
        $('#editform #name').val(name)
        $('#editform #slug').val(slug)
        $('#editModal').data('id', id)



    })

    $(' .btn_opt_edit').on('click', function () {
        const id = $('#editModal').data('id')
        console.log(id);
        const name = $('#editform #name').val()
        const slug = $('#editform #slug').val()
        const parm = { id, name, slug }
        $.ajax({
            url: '/admin/category/edit',
            type: 'post',
            data: parm,
            success(res) {

                $('#editModal').modal('hide')
                getCategoryList()
            }
        })
    })
    $(' .category_table').on('click', '.delete', function () {
        layer.confirm("您确定删除吗", { title: "提示" }, (index) => {
            const id = $(this).data("id");
            console.log(id);
            $.post("/admin/category/delete", { id }, function (res) {
                getCategoryList()
                layer.close(index);
            })
        })
    })
})
